<?php
namespace app\common\library\util;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class Token{
    protected static $key = '3P68n7';
    public static function generateToken($tokenData=[],$hour=24){
        $currentTime = time();
        $data = [
            "iss" => self::$key,        //签发者 可以为空
            "aud" => '',             //面象的用户，可以为空
            "iat" => $currentTime,   //签发时间
            "nbf" => $currentTime,   //立马生效
            "exp" => $currentTime + 60*60*$hour, //token 过期时间 1小时
            "data" => $tokenData,
        ];
        $token = JWT::encode($data,self::$key,"HS256");
        return $token;
    }
    public static function checkToken($token){
        $status = ["code"=>0];
        try{
            JWT::$leeway = 60;//当前时间减去60，把时间留点余地
            $decode = (array)JWT::decode($token,new Key(self::$key,"HS256"));
            $status["code"] = 1;
            $status["data"] = (array)$decode['data'];
            return $status;
        }catch(\Firebase\JWT\SignatureInvalidException $e) { //签名不正确
            $status['msg']="签名不正确";
            return $status;
        }catch(\Firebase\JWT\BeforeValidException $e) { // 签名在某个时间点之后才能用
            $status['msg']="token失效";
            return $status;
        }catch(\Firebase\JWT\ExpiredException $e) { // token过期
            $status['msg']="token失效";
            return $status;
        }catch(\Exception $e) { //其他错误
            $status['msg']="未知错误";
            return $status;
        }
    }
}